import json
import sys 
reload(sys)
sys.setdefaultencoding("utf-8") 
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'godness.settings'
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
from renren.models import *
Lambda = 0.2
data_path = "../renren/res.json"
facejoking_path = "../facejoking/face.json"
def load_data(filename,face_filename):
	fin2 =open(face_filename)
	faces = json.loads(fin2.read())
	F={}
	for face in faces:
		F[face['name']] = (face['face_rate'],face['image_urls'],face['school'],face['gender'])
	fin = open(filename)
	renrens = json.loads(fin.read())
	views=[]
	for renren in renrens:	
		try:	
			views.append(int(renren['numberOfViews']))
			tmp = Renren.objects.create(school = renren['school'],name = renren['name'],
				gender=renren['gender'],numberOfFriends=renren['numberOfFriends'],
				url=renren['url'],renrenID=renren['ID'])
			try:
				tmp.numberOfViews = renren['numberOfViews']
			except:
				pass
			try:
				tmp.image_urls = renren['image_urls'][0]
			except:
				pass
			try:
				tmp.birthyear = renren['birthyear'][0]
			except:
				pass
			try:
				tmp.birthmonth = renren['birthmonth'][0]
			except:
				pass
			try:
				tmp.birthday =renren['birthday'][0]
			except:
				pass
			try:
				tmp.hometown = renren['hometown'][0]
			except:
				pass
			try:
				tmp.department =renren['department'][0]
			except:
				pass
			try:
				tmp.constellation = renren['constellation'][0]
			except:
				pass
			if renren['name'] in F:
				print F[renren['name']]
				tmp.face_rate = F[renren['name']][0]
				F[renren['name']] = -1
			tmp.save()
		except ValueError:
			print "ValueError"
		except:
			print "error"
	fin.close()
	fin2.close()
	cnt = -1
	for (k,v) in F.items():
		if v!=-1:
			tmp = Renren.objects.create(school = v[2],name = k,
				gender=v[3],
				image_urls=v[1][0],face_rate=v[0],renrenID=cnt)
		cnt-=1
	views.sort(reverse = True)
	for r in Renren.objects.all():
		ranking = 0
		rates=0
		if r.face_rate == 1000000:
			rates=0
		else:
			rates=views[r.face_rate]
		r.ranking = Lambda*rates+(1.0-Lambda)*r.numberOfViews
		r.save()
load_data(data_path,facejoking_path)